package com.lyn.pack_lyn_jar_aar;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.RectF;
import android.hardware.Camera;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.ImageView;

import com.lyn.image.ImageNative;
import com.lyn.qrcode.QrCode;
import com.lyn.qrcode.QrCodeManager;
import com.lyn.utils.BindViewUtil;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements Camera.PreviewCallback {

    @BindViewUtil.BindView(id = R.id.surfaceView)
    private SurfaceView surfaceView;
    @BindViewUtil.BindView(id = R.id.image)
    private ImageView image;
    @BindViewUtil.BindView(id = R.id.image2)
    private ImageView image2;
    private Camera camera;
    private SurfaceHolder holder;
    private ExecutorService executorService;
    private SurfaceHolder holder1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            BindViewUtil.scanning(this);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        holder = surfaceView.getHolder();
        holder.addCallback(callback);
        executorService = Executors.newSingleThreadExecutor();
    }

    private SurfaceHolder.Callback callback = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
            try {
                openCamera();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {

        }

        @Override
        public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
            closeCamera();
        }
    };


    private void openCamera() throws Exception {
        camera = Camera.open(0);
        Camera.Parameters parameters = camera.getParameters();
        parameters.setPreviewSize(640, 480);
        camera.setParameters(parameters);
        camera.setPreviewDisplay(holder);
        Camera.Size size = parameters.getPreviewSize();
        camera.addCallbackBuffer(new byte[size.width * size.height * 3 / 2]);
        camera.setPreviewCallbackWithBuffer(this);
        camera.startPreview();

    }

    private void closeCamera() {
        if (camera != null) {
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }

    @Override
    public void onPreviewFrame(byte[] bytes, Camera camera) {
        try {
            detectQRCode(bytes, camera);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            camera.addCallbackBuffer(bytes);
        }

    }

    private final ImageNative imageNative = new ImageNative();

    private boolean isDetect = true;

    private void detectQRCode(byte[] bytes, Camera camera) {
        Camera.Parameters parameters = camera.getParameters();
        Camera.Size size = parameters.getPreviewSize();
        Bitmap bitmap1 = imageNative.nv21ToBitmap(bytes, size.width, size.height);
        image.setImageBitmap(bitmap1);
        List<QrCode> qrCodes = QrCodeManager.getInstance().scanNv21(bytes, size.width, size.height);
        if (qrCodes.size() < 1) {
            return;
        }
        QrCode qrCode = qrCodes.get(0);
        Rect rect = qrCode.getRect();
        byte[] nv21 = imageNative.cutNV21(qrCode.getNv21Data(), size.width, size.height
                , rect.left, rect.top
                , rect.right - rect.left, rect.bottom - rect.top);
        Bitmap bitmap = imageNative.nv21ToBitmap(nv21, rect.right - rect.left, rect.bottom - rect.top);
        image2.setImageBitmap(bitmap);
        int[] rgb = new int[bitmap.getWidth() * bitmap.getHeight()];
        bitmap.getPixels(rgb, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
        Log.i("lyn", "left:" + rect.left + "top:" + rect.top + "right:" + rect.right + "bottom:" + rect.bottom);
        for (int i = 0; i < rgb.length; i++) {
            int color = rgb[i];
            int red = (color & 0xff0000) >> 16;
            int green = (color & 0x00ff00) >> 8;
            int blue = (color & 0x0000ff);
            Log.i("lyn", "红色:" + red + "绿色:" + green + "蓝色:" + blue);
        }
    }

    private final static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .build();
    private final static MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

    private void networkRequest(String url) throws Exception {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        boolean successful = response.isSuccessful();
        if (!successful) {
            Log.i("lyn", "请求失败!");
            return;
        }
        String result = response.body().string();
        Log.i("lyn", "请求结果:" + result);
    }


}